

package com.sixfoot.adminsys.frames.scale;

import com.sixfoot.adminsys.DemoProperties;
import com.sixfoot.adminsys.frames.Stacker;
import com.sixfoot.adminsys.utilities.UIUtils;
import com.sixfoot.dao.ScaleRepository;
import com.sixfoot.domain.scale.Scale;

import javax.swing.*;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.*;
import javax.swing.text.Document;
import java.awt.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import static com.sixfoot.adminsys.frames.scale.ScaleTableModel.*;


@DemoProperties(value = "记录列表",
		category = "用户记录管理",
		description = ""
    )
public class ScaleTable extends JPanel {
	private ScaleRepository scaleRepository = (ScaleRepository) UIUtils.getBean("scaleRepository");
	private JPanel controlPanel;
	private Stacker dataPanel;
	private JTable scaleTable;
	private JTextField filterField;
	private JLabel tableStatus;

	private Color[] rowColors;
	private String searchLabelString;

	private String filterString = null;

	private TableRowSorter sorter;
	private RowFilter<ScaleTableModel, Integer> searchFilter;
	private ScaleTableModel scaleTableModel;

	public ScaleTable() {
		initModel();
		initComponents();
		initSortingFiltering();
	}

	protected void initModel() {
		scaleTableModel = new ScaleTableModel();

	}

	protected void initComponents() {
		setLayout(new BorderLayout());

		controlPanel = createControlPanel();
		add(controlPanel, BorderLayout.NORTH);

		// <snip>Create JTable
		scaleTable = new JTable(scaleTableModel);
		// </snip>

		// </snip>Set JTable display properties
		scaleTable.setColumnModel(createColumnModel());
		scaleTable.setAutoCreateRowSorter(true);
		scaleTable.setRowHeight(26);
		scaleTable.setAutoResizeMode(JTable.AUTO_RESIZE_NEXT_COLUMN);
		scaleTable.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
		scaleTable.setIntercellSpacing(new Dimension(0, 0));
		// </snip>

		// <snip>Initialize preferred size for table's viewable area
		Dimension viewSize = new Dimension();
		viewSize.width = scaleTable.getColumnModel().getTotalColumnWidth();
		viewSize.height = 10 * scaleTable.getRowHeight();
		scaleTable.setPreferredScrollableViewportSize(viewSize);
		// </snip>

		// <snip>Customize height and alignment of table header
		JTableHeader header = scaleTable.getTableHeader();
		header.setPreferredSize(new Dimension(30, 26));
		TableCellRenderer headerRenderer = header.getDefaultRenderer();
		if (headerRenderer instanceof JLabel) {
			((JLabel) headerRenderer).setHorizontalAlignment(JLabel.CENTER);
		}
		// </snip>

		JScrollPane scrollpane = new JScrollPane(scaleTable);
		dataPanel = new Stacker(scrollpane);
		add(dataPanel, BorderLayout.CENTER);

		add(createStatusBar(), BorderLayout.SOUTH);

	}

	protected JPanel createControlPanel() {
		JPanel controlPanel = new JPanel();
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints c = new GridBagConstraints();
		controlPanel.setLayout(gridbag);

		c.gridx = 0;
		c.gridy = 1;
		c.gridheight = 1;
		c.insets = new Insets(20, 10, 0, 10);
		c.anchor = GridBagConstraints.SOUTHWEST;
		JLabel searchLabel = new JLabel("输入用户姓名名或记录类型进行搜索");
		controlPanel.add(searchLabel, c);

		c.gridx = 0;
		c.gridy = 2;
		c.weightx = 1.0;
		c.insets.top = 0;
		c.insets.bottom = 12;
		c.anchor = GridBagConstraints.SOUTHWEST;
		// c.fill = GridBagConstraints.HORIZONTAL;
		filterField = new JTextField(24);
		filterField.getDocument().addDocumentListener(
				new SearchFilterListener());
		controlPanel.add(filterField, c);

		c.gridx = 1;
		c.gridy = 2;
		c.gridwidth = GridBagConstraints.REMAINDER;
		// c.insets.right = 24;
		// c.insets.left = 12;
		c.weightx = 0.0;
		c.anchor = GridBagConstraints.EAST;
		c.fill = GridBagConstraints.NONE;

		return controlPanel;
	}

	protected class SearchFilterListener implements DocumentListener {
		protected void changeFilter(DocumentEvent event) {
			Document document = event.getDocument();
			try {
				setFilterString(document.getText(0, document.getLength()));

			} catch (Exception ex) {
				ex.printStackTrace();
				System.err.println(ex);
			}
		}

		public void changedUpdate(DocumentEvent e) {
			changeFilter(e);
		}

		public void insertUpdate(DocumentEvent e) {
			changeFilter(e);
		}

		public void removeUpdate(DocumentEvent e) {
			changeFilter(e);
		}
	}

	protected Container createStatusBar() {
		searchLabelString = "记录数 ";

		Box statusBar = Box.createHorizontalBox();


		// Middle (should stretch)
		statusBar.add(Box.createHorizontalGlue());
		statusBar.add(Box.createHorizontalGlue());
		statusBar.add(Box.createVerticalGlue());

		// Right status area
		tableStatus = new JLabel(searchLabelString +"0");
		statusBar.add(tableStatus);
		statusBar.add(Box.createHorizontalStrut(12));
	 	scaleTableModel.addTableModelListener(new TableModelListener() {
			public void tableChanged(TableModelEvent e) {
				// Get rowCount from *table*, not model, as the view row count
				// may be different from the model row count due to filtering
				tableStatus.setText(searchLabelString + scaleTable.getRowCount());
			}
		});

		return statusBar;
	}

	private Color[] getTableRowColors() {
		if (rowColors == null) {
			rowColors = new Color[2];
			rowColors[0] = UIManager.getColor("Table.background");
			rowColors[1] = new Color((int) (rowColors[0].getRed() * .9),
					(int) (rowColors[0].getGreen() * .9),
					(int) (rowColors[0].getBlue() * .9));
		}
		return rowColors;
	}


	public void start() {
		loadData();
	}

	// <snip>Initialize table columns
	protected TableColumnModel createColumnModel() {
		DefaultTableColumnModel columnModel = new DefaultTableColumnModel();
		TableCellRenderer cellRenderer = new ScaleCellRenderers.RowRenderer(
				getTableRowColors());
		TableColumn column = new TableColumn();
		column.setModelIndex(user_column);
		column.setHeaderValue("用户");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(resource_column);
		column.setHeaderValue("类型");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(difficulty_column);
		column.setHeaderValue("难度");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(starttime_column);
		column.setHeaderValue("开始时间");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(stoptime_column);
		column.setHeaderValue("结束时间");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(pulsation_column);
		column.setHeaderValue("脉搏");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(hrv_column);
		column.setHeaderValue("心率变异性");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(artifact_column);
		column.setHeaderValue("伪信号");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(ibi_column);
		column.setHeaderValue("即时心率");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(ppg_column);
		column.setHeaderValue("频谱");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(ep_column);
		column.setHeaderValue("评价");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(remark_column);
		column.setHeaderValue("用户备注");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(timedomain_column);
		column.setHeaderValue("时域");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(frequencydomain_column);
		column.setHeaderValue("频域");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		column = new TableColumn();
		column.setModelIndex(evaluation_column);
		column.setHeaderValue("最终评价");
		column.setCellRenderer(cellRenderer);
		columnModel.addColumn(column);

		return columnModel;
	}

	// </snip>

	// <snip>Use SwingWorker to asynchronously load the data

	public void loadData() {
		List<Scale> scales = new ArrayList<>();
		Iterable<Scale> iterable = scaleRepository.findAll();
		Iterator<Scale> iterator = iterable.iterator();
		while (iterator.hasNext()) {
			scales.add(iterator.next());
		}
		scaleTableModel.add(scales);
	}

	public void setFilterString(String filterString) {
		String oldFilterString = this.filterString;
		this.filterString = filterString;
		if (filterString != null && !filterString.equals("")) {
			sorter.setRowFilter(searchFilter);
		} else {
			sorter.setRowFilter(null);
		}
		tableStatus.setText(searchLabelString + scaleTable.getRowCount());
		firePropertyChange("filterString", oldFilterString, filterString);
	}

	protected void initSortingFiltering() {
		// <snip>Setup filtering for winners
		sorter = new TableRowSorter(scaleTableModel);
		scaleTable.setRowSorter(sorter);
		// </snip>

		// <snip>Setup search filter
		searchFilter = new RowFilter<ScaleTableModel, Integer>() {
			public boolean include(
					Entry<? extends ScaleTableModel, ? extends Integer> entry) {
				ScaleTableModel scaleTableModel = entry.getModel();
				Scale scale = scaleTableModel.getScale(entry
						.getIdentifier().intValue());
				boolean matches = false;

				String realName = scale.getUser().getRealName();
				if (realName != null) {
					// Returning true indicates this row should be shown.
					matches = realName.contains(filterString);
					if (matches) {
						return matches;
					}
				}
				String resource = scale.getResource().getName();
				if (resource != null) {
					// Returning true indicates this row should be shown.
					matches = resource.contains(filterString);
				}
				return matches;
			}
		};
		// </snip>
	}

	public static void main(String args[]) {

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				JFrame frame = new JFrame("JTable Demo");
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				ScaleTable demo = new ScaleTable();
				frame.add(demo);
				frame.setSize(700, 400);
				frame.setVisible(true);
				demo.start();
			}
		});
	}
}